#include <windows.h>
#include "fileio.h"

BOOL LoadTextFileToEdit(HWND hEdit, LPWSTR pwszFileName)
{
	HANDLE hFile;
	BOOL bSuccess = FALSE;

	hFile = CreateFile(
		pwszFileName, 
		GENERIC_READ,
		FILE_SHARE_READ,
		NULL,
		OPEN_EXISTING,
		0,
		NULL);

	if(hFile == INVALID_HANDLE_VALUE)
		return false;

	DWORD dwFileSize;

	dwFileSize = GetFileSize(hFile, NULL);
	if(dwFileSize == 0xFFFFFFFF)
		return false;

	PVOID pszFileText;
	pszFileText = GlobalAlloc(GPTR, dwFileSize + 2);
	if(pszFileText == NULL)
		return false;

	DWORD dwRead;

	if(!ReadFile(hFile, pszFileText, dwFileSize, &dwRead, NULL))
		return false;

	int pi = IS_TEXT_UNICODE_UNICODE_MASK;
	if(IsTextUnicode(pszFileText, dwFileSize, &pi)) 
			SetWindowTextW(hEdit, (PWSTR)pszFileText);
	else 
			SetWindowTextA(hEdit, (PCSTR)pszFileText);
	
	GlobalFree(pszFileText);

	CloseHandle(hFile);

	return true;
}

BOOL DisplayLastError(DWORD dwError)
{
	LPWSTR lpMsgBuf;
	FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPWSTR)&lpMsgBuf, 0, NULL);
	MessageBox(NULL, lpMsgBuf, L"Application Error", MB_OK|MB_ICONINFORMATION );
	LocalFree(lpMsgBuf);
	return FALSE;
}

BOOL SaveTextFileFromEdit(HWND hEdit, LPWSTR pwszFileName)
{
	HANDLE hFile;
	BOOL bSuccess = false;
	int res = 0;

	hFile = CreateFile(pwszFileName, GENERIC_WRITE, 0, NULL, OPEN_ALWAYS,  FILE_ATTRIBUTE_NORMAL, NULL);

	if(hFile == INVALID_HANDLE_VALUE)
		return DisplayLastError(GetLastError());

	DWORD dwTextLength;
	dwTextLength = GetWindowTextLength(hEdit);

	if(dwTextLength < 1) {
		DisplayLastError(GetLastError());
		CloseHandle(hFile);
		return false;
	}

	LPWSTR pwszFileText;
	pwszFileText = (LPWSTR)GlobalAlloc(GPTR, (dwTextLength + 1) * sizeof(WCHAR));
	res = GetWindowText(hEdit, pwszFileText, dwTextLength + 1);

	if(res != dwTextLength) {
		DisplayLastError(GetLastError());
		CloseHandle(hFile);
		return FALSE;
	}

	DWORD dwBytesWritten;
	res = WriteFile(hFile, pwszFileText, dwTextLength * sizeof(WCHAR), &dwBytesWritten, NULL);

	if(res == 0) {
		DisplayLastError(GetLastError());
		CloseHandle(hFile);
		return FALSE;
	}

	CloseHandle(hFile);

	return TRUE;
}
